<template>
  <ContentCard>
    <template #header>
      <pageHeaderNew
        :title="`${form.id ? '编辑' : '新增'}工作日历`"
        :breadCrumb="breadCrumb"
        showBack
      ></pageHeaderNew>
    </template>
    <div class="wrap">
      <main>
        <header>
          <h2>基本信息</h2>
        </header>
        <a-form
          ref="formRef"
          :model="form"
          autoLabelWidth
          label-align="right"
          style="width: 50%; margin: 0 auto"
          :rules="rules"
        >
          <a-form-item field="name" label="工作日历名称" required show-colon>
            <a-input v-model="form.name" />
          </a-form-item>
          <a-form-item label="工作日历类型" required show-colon>
            <a-select
              v-model="form.type"
              :options="[
                { value: 1, label: '按周休息' },
                { value: 2, label: '按月休息' },
                { value: 3, label: '无固定休息日' }
              ]"
            />
          </a-form-item>
          <a-form-item label="">
            <div style="margin: 0 auto; margin-top: 0">
              <a-checkbox-group
                v-model:model-value="form.dayOff.week"
                v-if="form.type === 1"
              >
                <a-checkbox style="margin-bottom: 10px" :value="1">
                  周一{{ isRest(1) }}
                </a-checkbox>
                <a-checkbox style="margin-bottom: 10px" :value="2">
                  周二{{ isRest(2) }}
                </a-checkbox>
                <a-checkbox style="margin-bottom: 10px" :value="3">
                  周三{{ isRest(3) }}
                </a-checkbox>
                <a-checkbox style="margin-bottom: 10px" :value="4">
                  周四{{ isRest(4) }}
                </a-checkbox>
                <a-checkbox style="margin-bottom: 10px" :value="5">
                  周五{{ isRest(5) }}
                </a-checkbox>
                <a-checkbox style="margin-bottom: 10px" :value="6">
                  周六{{ isRest(6) }}
                </a-checkbox>
                <a-checkbox style="margin-bottom: 10px" :value="0">
                  周日{{ isRest(7) }}
                </a-checkbox>
              </a-checkbox-group>
              <a-space direction="vertical" v-else-if="form.type === 2">
                <a-space
                  v-for="(day, index) in form.dayOff.monthly"
                  :key="day.id"
                >
                  每月
                  <a-input-number
                    :min="1"
                    :max="31"
                    :model-value="day"
                    :style="{ flex: 1 }"
                    allow-clear
                    hide-button
                    @change="($event) => checkMonthly($event as number, index)"
                  >
                    <template #suffix> 日 </template>
                  </a-input-number>
                  休息
                  <icon-plus-circle
                    size="18"
                    style="color: #7abbff; cursor: pointer; margin: 0 10px"
                    @click="form.dayOff.monthly.push(0)"
                  />
                  <icon-delete
                    v-if="index"
                    size="18"
                    style="color: #ff6565; cursor: pointer"
                    @click="del(index)"
                  />
                </a-space>
              </a-space>
              <a-space direction="vertical" v-else-if="form.type === 3">
                <a-space>
                  每月共有
                  <a-input-number
                    v-model="form.dayOff.days"
                    :style="{ flex: 1 }"
                    allow-clear
                    hide-button
                  >
                    <template #suffix> 日 </template>
                  </a-input-number>
                  休息
                </a-space>
              </a-space>
            </div>
          </a-form-item>
          <a-form-item label="使用范围" show-colon>
            <a-textarea v-model="form.scope" />
          </a-form-item>
          <a-form-item label="法定节假日自动排休" show-colon required>
            <a-switch
              v-model="form.isSynchronization"
              :checkedValue="1"
              :uncheckedValue="2"
            />
          </a-form-item>
        </a-form>
        <header
          style="
            display: flex;
            justify-content: space-between;
            align-items: flex-end;
            padding-bottom: 5px;
          "
        >
          <h2>特殊日期设置</h2>
          <a-radio-group
            v-model="type"
            style="height: 25px"
            default-value="Beijing"
            type="button"
            size="mini"
          >
            <a-radio :value="1">年</a-radio>
            <a-radio :value="2">月</a-radio>
            <a-radio :value="3">周</a-radio>
          </a-radio-group>
        </header>
        <Calendar
          :type="type"
          :week="form.dayOff.week"
          :monthly="form.dayOff.monthly"
          :vacationType="form.type"
          :isSynchronization="form.isSynchronization"
          v-model:specialSetting="form.attendanceWorkCalendarSpecialSetting"
        />
      </main>
      <footer>
        <a-button
          class="btn"
          style="
            margin-right: 20px;
            border: 1px rgba(242, 242, 242, 1) solid;
            background-color: #fff;
          "
          @click="$router.go(-1)"
          >返回</a-button
        >
        <a-button class="btn" type="primary" @click="save">保存</a-button>
      </footer>
    </div>
  </ContentCard>
</template>
<script setup lang="ts">
import Calendar from './Calendar.vue';
import { Message } from '@arco-design/web-vue';
import { cloneDeep } from 'lodash';
import {
  PostWorkCalendar,
  PutWorkCalendar,
  GetWorkCalendarRepeat
} from '@/apis/attendance/base-setting/index';

const type = ref<1 | 2 | 3>(1);
const breadCrumb: string[] = ['考勤', '基础设置', '考勤设置', '工作日历设置'];
const formRef = ref();

const form = reactive<any>({
  type: 1,
  isSynchronization: 2,
  attendanceWorkCalendarSpecialSetting: [],
  dayOff: { week: [], monthly: [0], days: 0 }
});

watch(
  () => form.type,
  () => {
    form.dayOff.week = [];
    form.dayOff.monthly.length = 0;
    Object.assign(form.dayOff.monthly, [0]);
    form.dayOff.days = 0;
  }
);

const isRest = (value: number) => {
  if (form.dayOff.week.includes(value)) return '(休息)';
  return '';
};

const validateName = async (val: string, cb: any) => {
  try {
    if (form.id && form.name === val) {
      return;
    } else {
      const res = await GetWorkCalendarRepeat({
        name: val
      });
      if (res.code) cb(`${res.msg}`);
    }
  } catch (error: unknown) {
    console.log(error);
  }
};
const rules = {
  name: [
    {
      required: true,
      message: '请填写名称',
      trigger: "['change', 'input', 'blur']"
    },
    {
      validator: validateName
    }
  ]
};
const checkMonthly = (e: number | 0, index: number) => {
  let list = cloneDeep(form.dayOff.monthly);
  if (list.some((i: number) => i === e)) {
    return Message.error('所选日期有重复');
  } else {
    list[index] = e;
  }
  form.dayOff.monthly = list;
};
const del = (index: number) => {
  let list = cloneDeep(form.dayOff.monthly);
  list.splice(index, 1);
  form.dayOff.monthly = list;
};
onMounted(() => {
  Object.assign(form, JSON.parse(localStorage.getItem('calendarData') + ''));
});

const save = async () => {
  try {
    if (await formRef.value.validate()) return;
    if (form.id) {
      await PutWorkCalendar(form);
    } else {
      await PostWorkCalendar(form);
    }
  } catch (error) {
    console.log(error);
  }
};
onUnmounted(() => {
  localStorage.removeItem('calendarData');
});
</script>
<style lang="less" scoped>
.wrap {
  main {
    margin-bottom: 60px;
    overflow: hidden;

    header {
      border-bottom: 1px solid #f2f2f2;
      margin-bottom: 20px;
    }
    header h2 {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
    }
    header h2::before {
      content: '';
      display: inline-block;
      width: 7px;
      height: 30px;
      background-color: #165dff;
      margin-right: 10px;
    }
  }
  footer {
    height: 60px;
    width: calc(100% - 100px);
    background-color: #fff;
    box-shadow: 1px -1px 10px 0 #cacaca;
    position: fixed;
    bottom: 0;
    left: 10%;
    display: flex;
    justify-content: center;
    align-items: center;

    .btn {
      width: 120px;
      height: 40px;
      border-radius: 5px;
    }
  }
}
</style>
